package com.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.app.common.Result;
import com.app.mapper.*;
import com.app.model.*;
import com.app.service.AdminUserService;
import com.app.service.AreaService;
import com.app.service.BusinessSettledService;
import com.app.utils.CommonHelp;
import com.app.vo.BusinessSettledVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static org.apache.commons.codec.digest.DigestUtils.md5Hex;

/**
 * <p>
 * 商家入驻表 服务实现类
 * </p>
 *
 * @author 16693103420
 * @since 2024-01-26
 */
@Service
public class BusinessSettledServiceImpl extends ServiceImpl<BusinessSettledMapper, BusinessSettledModel> implements BusinessSettledService {

    @Autowired
    private BusinessSettledMapper businessSettledMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private AreaService areaService;
    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CityMapper cityMapper;
    @Autowired
    private AreaMapper areaMapper;
    @Autowired
    public ProvinceMapper provinceMapper;
    @Autowired
    private UserServiceImpl userServiceImpl;

    @Autowired
    private AdminUserService adminUserService;

    //查询列表
    @Override
    public BusinessSettledVo getBusinessSettledList(Integer page, Integer limit, String businessName,
                                                    String phone, Integer status, AdminUserModel user, Integer areaId) {
        Page<BusinessSettledModel> page1 = new Page<>(page, limit);
        QueryWrapper<BusinessSettledModel> qw = new QueryWrapper<>();
        if (StrUtil.isNotBlank(businessName)) {
            qw.like("business_name", businessName);
        }
        if (user.getRoleId() == 3) {
            qw.eq("city_id", areaId).or().eq("city_id", user.getAreaId());
        }
        if (user.getRoleId() == 4) {
            qw.eq("area_id", areaId).or().eq("area_id", user.getAreaId());
        }
        if (StrUtil.isNotBlank(phone)) {
            qw.like("phone", phone);
        }
        if (status != null) {
            qw.eq("status", status);
        }
        qw.orderByDesc("create_time");
        Page<BusinessSettledModel> BusinessSettledPage = businessSettledMapper.selectPage(page1, qw);
        List<BusinessSettledModel> BusinessSettledList = BusinessSettledPage.getRecords();
        for (BusinessSettledModel businessSettledModel : BusinessSettledList) {
            if (businessSettledModel.getType() != null) {
                CategoryModel categoryModel = categoryMapper.selectById(businessSettledModel.getType());
                if (categoryModel != null) {
                    businessSettledModel.setTypeText(categoryModel.getName());
                }
            }
            if (businessSettledModel.getAreaId() != null) {
                AreaModel areaModel = areaService.getById(businessSettledModel.getAreaId());
                if (areaModel != null) {
                    businessSettledModel.setAreaText(areaModel.getArea());
                }
            }
            //构建areaText
            String areaText;
            String businessAreaId = businessSettledModel.getAreaId();
            QueryWrapper<AreaModel> areaQW = new QueryWrapper<>();
            areaQW.eq("area_id", businessAreaId);
            AreaModel areaModel = areaMapper.selectOne(areaQW);
            areaText = areaModel.getArea();
            if (businessSettledModel.getCityId() != null) {
                CityModel cityModel = cityMapper.selectOne(new QueryWrapper<CityModel>()
                        .eq("city_id", businessSettledModel.getCityId()));
                String city = cityModel.getCity();
                ProvinceModel provinceModel = provinceMapper.selectOne(new QueryWrapper<ProvinceModel>()
                        .eq("province_id", cityModel.getProvinceId()));
                areaText = provinceModel.getProvince() + "\\" + city + "\\" + areaText;
            }
            businessSettledModel.setAreaText(areaText);
        }
        long count = BusinessSettledPage.getTotal();
        BusinessSettledVo BusinessSettledVo = new BusinessSettledVo();
        BusinessSettledVo.setList(BusinessSettledList);
        BusinessSettledVo.setCount((int) count);
        return BusinessSettledVo;
    }

    /**
     * 当商家入住时，把商家信息同步到商家管理端
     *
     * @param id     入驻商家表的id
     * @param status 商家入驻状态
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateStatus(Integer id, Integer status) throws Exception {

        if (ObjectUtil.isNull(id) || ObjectUtil.isNull(status)) {
            return Result.error(405, "参数错误");
        }
        //根据入驻id查询入住的对象
        BusinessSettledModel businessSettled = getById(id);
        if (ObjectUtil.isEmpty(businessSettled)) {
            return Result.error(405, "商家不存在");
        }
        Integer userId = businessSettled.getUserId();
        if (ObjectUtil.isNull(userId)) {
            return Result.error(405, "用户不存在");
        }
        UserModel userModel = userMapper.selectById(userId);
        userModel.setStatus(2);
        String userPhone = userModel.getPhone();
        //根据对像中的手机号去管理的表中的区查询数据
        BusinessModel businessModel = businessMapper.selectByUserPhone(userPhone);
        businessSettled.setStatus(status);
        businessSettledMapper.updateById(businessSettled);
        if (ObjectUtil.isNotEmpty(businessModel)) {//商家信息已经存在  提示已入住不能重复入驻
            //修改商家管理端的入驻状态
            if (status.equals(businessModel.getStatus())) {
                return Result.error(400, "商家已操作成功");
            }
            businessModel.setUpdateTime(CommonHelp.getNowTimestamp());
            businessModel.setUserPhone(userPhone);
            businessModel.setBusinessPhone(businessSettled.getPhone());
            businessModel.setBusinessFace(businessSettled.getLogo());
            businessModel.setStatus(status);
            businessModel.setAreaId(businessSettled.getAreaId());
            businessModel.setCityId(businessSettled.getCityId());
            businessModel.setAreaCode(businessSettled.getAreaCode());
            businessModel.setCustomerServiceId(businessSettled.getCustomerServiceId());
            businessMapper.updateById(businessModel);
            //取消会员身份
            userModel.setVip(2);
            userMapper.updateById(userModel);
            return Result.success("");//商家退出入驻、入驻成功
        } else {
            //向商家管理表格中新增
            BusinessModel businessModelSave = BeanUtil.copyProperties(businessSettled, BusinessModel.class);
            businessModelSave.setCreateTime(CommonHelp.getNowTimestamp());
            businessModelSave.setUserPhone(userPhone);
            businessModelSave.setBusinessStatus(2);
            businessModelSave.setBusinessPhone(businessSettled.getPhone());
            businessModelSave.setBusinessFace(businessSettled.getLogo());
            businessModelSave.setStatus(status);
            businessModelSave.setAreaId(businessSettled.getAreaId());
            businessModelSave.setCityId(businessSettled.getCityId());
            businessModelSave.setAreaCode(businessSettled.getAreaCode());
            businessModelSave.setCustomerServiceId(businessSettled.getCustomerServiceId());
            businessMapper.insert(businessModelSave);

            QueryWrapper<AdminUserModel> adminUserModelQueryWrapper = new QueryWrapper<>();
            adminUserModelQueryWrapper.eq("phone", businessSettled.getPhone());
            AdminUserModel exist = adminUserService.getOne(adminUserModelQueryWrapper);
            if (exist == null) {
                AdminUserModel adminUserModel = new AdminUserModel();
                adminUserModel.setUsername(userPhone);
                adminUserModel.setRealName(businessSettled.getBusinessName() + "管理员");
                adminUserModel.setRoleId(2);
                adminUserModel.setPhone(userPhone);
                adminUserModel.setStatus(1);
                adminUserModel.setRoleName("商家管理员");
                adminUserModel.setBusinessId(businessModelSave.getId());
                String salt = "suBei_bz";
                String newWord = md5Hex("ylb_" + businessSettled.getPhone() + salt);
                adminUserModel.setPassword(newWord);
                this.adminUserService.save(adminUserModel);
            }
            userServiceImpl.updateUserInfo(userModel);
            return Result.success("");//商家入驻成功
        }
    }

}
